<template>
    <div id="detail">
        <detail-nav-bar @itemClick="titleClick" :current-index="currentIndex"></detail-nav-bar>
        <scroll class="content"
                ref="Scroll"
                @scrollPosition="contentScroll"
                :data="[topImages, goods, shop, detailInfo, paramInfo, commentInfo, recommendList]"
                :obj="obj">
            <div>
                <detail-swiper  :images="topImages"></detail-swiper>
                <detail-base-info :goods="goods"></detail-base-info>
                <detail-shop-info :shop="shop"></detail-shop-info>
                <detail-goods-info :detail-info="detailInfo" @itemLoad="goodsImgLoaded"></detail-goods-info>
                <detail-param-info ref="param" :paramInfo="paramInfo"></detail-param-info>
                <detail-comment-info ref="comment" :comment-info="commentInfo"></detail-comment-info>
                <goods-list :goods="recommendList" ref="recommend"></goods-list>
            </div>
        </scroll>
        <detail-bottom-bar @addToCart="addToCart"></detail-bottom-bar>
        <back-top @click.native="backTop" v-show="isShowBackTop"></back-top>
        <toast message="添加成功" :isShow="toastShow"></toast>
    </div>
</template>

<script>
    import Scroll from 'components/common/scroll/Scroll'

    import DetailNavBar from './childComps/DetailNavBar'
    import DetailSwiper from './childComps/DetailSwiper'
    import DetailBaseInfo from './childComps/DetailBaseInfo'
    import DetailShopInfo from './childComps/DetailShopInfo'
    import DetailGoodsInfo from './childComps/DetailGoodsInfo'
    import DetailParamInfo from './childComps/DetailParamInfo'
    import DetailCommentInfo from './childComps/DetailCommentInfo'
    import DetailBottomBar from './childComps/DetailBottomBar'

    import GoodsList from 'components/content/goods/GoodsList'
    import BackTop from 'components/content/backtop/BackTop'

    import {getDetail, getRecommend, Goods, Shop, GoodsParam} from 'network/detail';
    import {debounce} from 'common/utils'
    
    export default {
        name:'Detail',
        components: {
            DetailNavBar,
            Scroll,
            DetailSwiper,
            DetailBaseInfo,
            DetailShopInfo,
            DetailGoodsInfo,
            DetailParamInfo,
            DetailCommentInfo,
            DetailBottomBar,
            BackTop,
            GoodsList,
        },
        data(){
            return{
                iid : null,
                topImages:[],
                goods:{},
                shop: {},
                detailInfo: {},
                paramInfo: {},
                commentInfo: {},
                recommendList: [],
                obj:{click:true,probeType:2,pullUpLoad:true}, // pullUpLoad 是否可以上拉
                imageLoadListener:null,
                isShowBackTop: false,
                currentIndex: 0,
                toastShow: false
            }
        },
        created () {
            //由于app.vue里面设置了keep-alive，所以详情界面也会有keep-alive属性
            //这导致数据会不刷新:页面改变，created不会执行
            this._getDetailData()
            this._getRecommend()

            // 创建防抖函数
            this.getTopY = debounce(this._getOffsetTops, 100);
        },

        mounted () {
            const refresh = debounce(this.$refs.Scroll.refresh, 200);
            this.imageLoadListener = () => {
                refresh();
            }

            this.$bus.$on('itemImageLoad', this.imageLoadListener)
        },

        updated () {
            // 获取需要的四个offsetTop
            // 这样获取也有问题
        //   setTimeout(()=>{
        //     this._getOffsetTops();
        //     console.log(this.$refs.param.$el.offsetTop)
        //   }, 100)
          // updated 只有事先设置好的data变量，并且要在页面重新渲染数据完成后才进入updated方法
        },

        methods: {
            _getDetailData() {
		    // 1.获取iid
            const iid = this.$route.query.iid
            this.iid = iid

            // 2.请求数据
            getDetail(iid).then(res => {
                // 2.1.获取结果
                const data = res.data.result;
                // 2.2.获取顶部信息
                this.topImages = data.itemInfo.topImages;

                // 2.3.获取商品信息
                this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services);

                // 2.4.获取店铺信息
                this.shop = new Shop(data.shopInfo);

                // 2.5.获取商品信息
                this.detailInfo = data.detailInfo

                // 2.6.保存参数信息
                this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule);

                // 2.7.保存评论信息
                if (data.rate.list) {
                    this.commentInfo = data.rate.list[0];
                }
                })
            },

            _getRecommend() {
                getRecommend().then((res, error) => {
                    if (error) return
                    this.recommendList = res.data.data.list;
                })
            },

            titleClick(index) {
                // 点击按钮调整到对应位置
                // 不用单独设置 this.currentIndex = index
                // 因为跳转到对应位置后，会同一设置this.currentIndex
                this.$refs.Scroll.scrollTo(0, -this.themeTops[index], 100)
            },

            // 监听滚动
            contentScroll(position) {
                // 监听BackTop的显示
                this.isShowBackTop = position.y < -1000;
                // 监听滚动到何处
                this._listenScrollTheme(-position.y)
            },

            // goods里面的图片加载完成刷新better-scroll
            goodsImgLoaded() {
                this.imageLoadListener();
                // 在详情图片加载完成后进行获取offsetTop值 (其实可以使用锚点)
                this.getTopY();
            },

            // 回到顶部
            backTop() {
                this.$refs.Scroll.scrollTo(0 ,0 ,300);
            },

            // 获取4个按钮对应位置
            _getOffsetTops() {
                // 如何确认DOM的正确位置
                this.themeTops = [];
                this.themeTops.push(0)
                this.themeTops.push(this.$refs.param.$el.offsetTop)
                this.themeTops.push(this.$refs.comment.$el.offsetTop)
                this.themeTops.push(this.$refs.recommend.$el.offsetTop)
                this.themeTops.push(Number.MAX_VALUE)
            },

            // 判断滚动到何处
            _listenScrollTheme(y) {

                let le = this.themeTops ? this.themeTops.length : 0;
                for (let i = 0; i < le-1; i++) {
                    if (this.currentIndex !== i && (y >= this.themeTops[i] && y < this.themeTops[i+1])) {
                        // currentIndex = i 说明还在当前位置， 这样设置处于性能考虑
                        this.currentIndex = i;  // 滚动到其他地方，改变currentIndex
                        break;
                    }
                }
            },

            // 加入购物车
            addToCart() {
                const obj = {};
                // 放入对象信息
                obj.iid = this.iid;
                obj.imgUrl = this.topImages[0];
                obj.title = this.goods.title;
                obj.desc = this.goods.desc;
                obj.newPrice = this.goods.realPrice;
                // 添加到store中
                this.$store.dispatch('addCart', obj).then(res => {
                    this.toastShow = true;
                    setTimeout(() => {
                        this.toastShow = false;
                    }, 1500)
                });

            }

            // 点击推荐图片时，跳转到详情页bug解决
            // 由于当前route是  /detail，  当点击图片时，还是进入的/detail， 导致vue-router报错
            // 解决 在router的index.js中从写push方法

            // 由于/detail?iid 只是参数变了， vue会复用组件，导致组件的生命周期不会销毁
            // 解决方法
            // 1、通过watch 观察 '$route': function(to, from) {}重新请求新的数据
            // 2、通过beforeRouteLeave(to, from, next){}守卫监听路由改变
            // 3、给router-view 添加key属性， 动态改变key的值 （时间戳）
        },
        watch: {
            '$route': function(to, from) {
                this._getDetailData()
                this._getRecommend()

                // 创建防抖函数
                this.getTopY = debounce(this._getOffsetTops, 100);
            }
        }
    }
</script>

<style scoped>
    #detail {
        /* 设置这个， 覆盖tab-bar */
        height: 100vh;
        position: relative;
        z-index: 1;
        background-color: #fff;
    }
    

    /* .detail-nav {
        position: absolute;
        top: 0;
        z-index: 12;
    } */

    .content {
        position: absolute;
        top: 44px;
        bottom: 60px;
        overflow: hidden;  /* 加上这句代码， 让鼠标滚动消失*/
    }

</style>